package com.ruoyi.article.controller;

import com.ruoyi.article.domain.*;
import com.ruoyi.article.domain.vo.AppUserInfo;
import com.ruoyi.article.domain.vo.ArticleParam;
import com.ruoyi.article.domain.vo.LikeAndCollect;
import com.ruoyi.article.domain.vo.reviewData;
import com.ruoyi.article.service.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.common.CaptchaController;
import com.ruoyi.web.controller.system.SysLoginController;
import io.jsonwebtoken.Claims;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/uniApp/articleApi")
public class ArticleAPP extends BaseController{

    @Autowired
    private IZArticleService zArticleService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private IZLabelService zLabelService;

    @Autowired
    private CaptchaController captchaController;

    @Autowired
    private SysLoginController sysLoginController;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IZPraiseLogService zPraiseLogService;

    @Autowired
    private IZArticleReviewService zArticleReviewService;

    @Autowired
    private IZAattentionService attentionService;
    @Autowired
    private  IZAattentionService aattentionService;

    /**
     * 获取置顶文章
     * @return
     */
    @GetMapping("/listArticleByLabelTop")
    public AjaxResult listArticleTop()
    {
        List<ZArticle> articlesTop = zArticleService.getTopArticle();
        return success(articlesTop);
    }

    /**
     * 获取公告列表
     * @return
     */
    @GetMapping(value = "/listArticleNotice")
    public AjaxResult getArticleNotice()
    {

        SysNotice sysNotice = new SysNotice();
        //1:通知，2:公告
        //sysNotice.setNoticeType("1");都返回
        List<SysNotice> sysNotices = noticeService.selectNoticeList(sysNotice);
        return success(sysNotices);
    }

    /**
     * 获取公告详情
     * @param noticeId 公告ID
     * @return
     */
    @GetMapping(value = "/getNoticeById")
    public AjaxResult getNoticeById(Long noticeId)
    {
        SysNotice sysNotices = noticeService.selectNoticeById(noticeId);
        return success(sysNotices);
    }

    /**
     * 获取每日最新文章
     * @return
     */
    @GetMapping(value = "/getApiGetNewArticle")
    public AjaxResult getApiGetNewArticle()
    {
        List<ZArticle> newArticles = zArticleService.getNewArticle();
        return success(newArticles);
    }

    /**
     * 获取文章分类
     * @return
     */
    @GetMapping(value = "/getApiArticleClassify")
    public AjaxResult getApiArticleClassify()
    {
        List<ZLabel> articlesLabels = zLabelService.getArticleLabel();
        return success(articlesLabels);
    }

    /**
     * 获取文章分类置顶轮播图
     * id 标签id
     * @return
     */
    @GetMapping(value = "/getClassifyBanner")
    public AjaxResult getClassifyBanner(Long id)
    {
        List<ZArticle> articlesClassifyTop = zArticleService.getArticleClassifyTop(id);
        return success(articlesClassifyTop);
    }


    /**
     * 获取文章分类列表
     * id 标签id
     * @return@RequestBody
     */
    @GetMapping(value = "/getClassifyArticle")
    public AjaxResult getClassifyArticle(ArticleParam articleParam)
    {
        List<ZArticle> ClassifyArticleList = zArticleService.getClassifyArticle(articleParam);
        return success(ClassifyArticleList);
    }

    /**
     * 获取验证码
     */
    @GetMapping(value = "/getArticleCode")
    public AjaxResult getArticleCode() throws IOException {
        return captchaController.getCode(new Response());
    }

    /**
     * 登录
     */
    @PostMapping(value = "/getApiLogin")
    public AjaxResult getApiLogin(@RequestBody LoginBody loginBody) {
        return sysLoginController.login(loginBody);
    }

    /**
     * 注册
     */
    @PostMapping(value = "/getApiRegister")
    public AjaxResult getApiRegister(@RequestBody RegisterBody user) {
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }


    /**
     * 获取用户信息
     */
    @GetMapping(value = "/getUserInfo")
    public AjaxResult getUserInfo(@RequestHeader("token") String token) {
        return sysLoginController.getUserInfo(token);
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file,@RequestHeader("token") String token) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = chandleUser(token);
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }

    private LoginUser chandleUser(String token) {
        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = tokenService.parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = tokenService.getTokenKey(uuid);
                LoginUser user = redisCache.getCacheObject(userKey);
                return user;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 获取文章详情
     */
    @GetMapping(value = "/getArticleDetails/{id}")
    public AjaxResult getArticleDetails(@PathVariable("id") Long id) {
        ZArticle byIdArticle = zArticleService.getByIdArticle(id);
        return AjaxResult.success(byIdArticle);
    }

    /**
     * 文章点赞
     */
    @PostMapping(value = "/getArticleLike")
    public AjaxResult getArticleLike(@RequestBody ZPraiseLog Article) {
        //这里得到的是文章id
        Long articleId = Article.getArticleId();
        //前端传递的是'true'点赞 或'false'取消点赞
        String status = Article.getStatus();
        Long userId = Article.getUserId();
        return toAjax(zPraiseLogService.insertReviewArticleLike(articleId,status,userId));
    }

    //查询文章是否被点赞
    @PostMapping("/getArticleIsLike")
    public AjaxResult getIsLoveStar(@RequestBody LikeAndCollect likeAndCollect) {
        {
            Boolean flag = zPraiseLogService.getIsIsLike(likeAndCollect);
            return success(flag);
        }
    }

    //查询文章是否被收藏
    @PostMapping("/getArticleIsCollect")
    public AjaxResult isCollect(@RequestBody LikeAndCollect likeAndCollect)
    {
        Boolean flag = zPraiseLogService.getIsArticleCollect(likeAndCollect);
        return success(flag);
    }

    /**
     * 文章收藏
     */
    @PostMapping("/getArticleCollect")
    public AjaxResult addReviewLog(@RequestBody ZPraiseLog Article)
    {
        //这里得到的是文章id
        Long articleId = Article.getArticleId();
        //前端传递的是'true'收藏 或'false'取消收藏
        String status = Article.getStatus();
        Long userId = Article.getUserId();
        return toAjax(zPraiseLogService.insertArticleReviewLog(articleId,status,userId));
    }

    /**
     * 查询评论列表
     */
    @GetMapping("/getReviewList")
    public AjaxResult getReview(ZArticleReview zArticleReview)
    {

        List<reviewData> review = zArticleReviewService.getReviewList(zArticleReview);
        return success(review);
    }


    /**
     * 新增用户点赞日志记录
     */
    @PostMapping("/getArticleReviewLike")
    public AjaxResult getArticleReviewLike(@RequestBody ZArticleReview zArticleReview)
    {
        //这里得到的是评论记录的id
        Long id = zArticleReview.getId();
        Long contentId = zArticleReview.getContentId();
        Integer status = zArticleReview.getStatus();
        Long userId = zArticleReview.getUserId();
        String userName = zArticleReview.getUserName();
        return toAjax(zPraiseLogService.insertReviewLikeLog(id,contentId,status,userId,userName));
    }

    /**
     * 获取文章作者信息
     */
    @GetMapping(value = "/getArticAuthor/{articleId}")
    public AjaxResult getArticAuthor(@PathVariable("articleId") Long articleId) {
        AppUserInfo userInfo = zArticleService.getByIdArticleAuthor(articleId);
        return AjaxResult.success(userInfo);
    }


    /**
     * 新增一级评论
     */
    @PostMapping("/getArtiReviewOne")
    public AjaxResult add(@RequestBody ZArticleReview zArticleReview)
    {
        Long  reviewId = zArticleReviewService.insertReviewReviewId(zArticleReview);
        return success(reviewId);
    }

    /**
     * 新增二级评论
     */
    @PostMapping("/getArtiReviewTwo")
    public AjaxResult saveReview(@RequestBody ZArticleReview zArticleReview)
    {
        Long  reviewId = zArticleReviewService.saveReviewReviewId(zArticleReview);
        return success(reviewId);
    }

    /**
     * 删除评论
     */
    @GetMapping(value = "/getDelArticReview/{reviewId}")
    public AjaxResult getDelArticReview(@PathVariable("reviewId") Long reviewId) {
        return toAjax(zArticleReviewService.removeByIdTree(reviewId));
    }


    /**
     * 查看是否关注
     */
    @PostMapping("/getDelArticIsPassivity")
    public AjaxResult getDelArticIsPassivity(@RequestBody ZAttention zAattention)
    {
        Boolean  flag = attentionService.isPassivity(zAattention);
        return success(flag);
    }


    /**
     *
     */
    @PostMapping("/getDelArticPassivity")
    public AjaxResult getDelArticPassivity(@RequestBody ZAttention zAattention)
    {

        return toAjax(attentionService.passivity(zAattention));
    }

    /**
     * 查询当前用户的文章
     */
    @GetMapping(value = "/getArticByUserId/{id}")
    public AjaxResult getArticByUserId(@PathVariable("id") Long id) {
        List<ZArticle> articles = zArticleService.getArticleListById(id);
        return success(articles);
    }

    /**
     * 查询当前用户关注的作者
     */
    @GetMapping(value = "/getLikeList/{id}")
    public AjaxResult getLikeList(@PathVariable("id") Long id) {
        List<AppUserInfo> appUserInfos = aattentionService.getUserList(id);
        return success(appUserInfos);
    }
}
